/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import model.pojo.*;
import model.dao.*;
import model.util.MySQLProviders;

/**
 *
 * @author VuTienIT
 */
public class GioHang extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.removeAttribute("ThongBaoDH");
        String page = request.getParameter("Page");
        
        // Lấy giỏ hàng
        ArrayList<PhieuPOJO> gioHang = null;
        if(session.getAttribute("GioHang")==null)
        {
            gioHang = new ArrayList<PhieuPOJO>();
            session.setAttribute("GioHang", gioHang);
        }
        else
        {
            gioHang = (ArrayList<PhieuPOJO>)session.getAttribute("GioHang");
        }
        
        // Tạo Session đăng nhập cho khách hàng
        KhachHangPOJO ssDangNhap = null;
        if(session.getAttribute("KhachHang")==null)
        {
            ssDangNhap = new KhachHangPOJO();
            session.setAttribute("KhachHang", ssDangNhap);
        }
        else
        {
            ssDangNhap = (KhachHangPOJO)session.getAttribute("KhachHang");
        }
        
        ArrayList<PhieuPOJO> dsKMt = PhieuDAO.getDanhSachKMHnay3();
        request.setAttribute("PhieuKM", dsKMt);
        ArrayList<DanhMucPOJO> danhMucs = DanhMucDAO.getDanhSach();
        request.setAttribute("DanhMucS", danhMucs);
        
        if (page != null) 
        {   
            if(ssDangNhap.getTenTruyCap()==null)
            {
                response.sendRedirect("DangNhap");
            }
            else
            {
                if(page.equals("View")) 
                {                
                    request.getRequestDispatcher("/GioHang.jsp").forward(request, response);
                }
                if(page.equals("DatHang")) 
                {
                    request.getRequestDispatcher("/HoaDon.jsp").forward(request, response);
                }

                if(page.equals("Engage")) 
                {
                    //Xoá giày ra khỏi giỏ hàng
                    if(request.getParameter("btXoa")!=null)
                    {
                        String[] cacMaSachXoa = request.getParameterValues("cbXoa");
                        if(cacMaSachXoa != null)
                        {
                            /*
                             * Nếu ng` dùng nhấn nút xoá
                             * form sẽ gửi lên server các mã giầy cần xoá
                             * giá trị này nằm trong phần value của CheckBox cbXoa
                             */
                            for(int i=0;i<cacMaSachXoa.length;i++)
                            {
                                //Lấy 1 mã giày cần xoá
                                String ms = cacMaSachXoa[i];
                                //Tìm xem mã giày vừa lấy ra có trong giỏ hàng ko
                                for(int j=0;j<gioHang.size();j++)
                                {
                                    PhieuPOJO giay = gioHang.get(j);
                                    //Nếu có thì xoá nó ra khỏi giỏ hàng
                                    if(giay.getMaPhieu()==Integer.parseInt(ms))
                                    {
                                        gioHang.remove(j); 
                                        break;
                                    }
                                }
                            }
                        }
                        request.getRequestDispatcher("GioHang?Page=View").forward(request, response);
                    }
                    
                    //Xoá giày ra khỏi giỏ hàng
                    if(request.getParameter("btnXoaTatCa")!=null)
                    {
                        for(int j=0;j<gioHang.size();j++)
                        {
                            gioHang.remove(j); 
                            //break;
                        }
                        request.getRequestDispatcher("GioHang?Page=View").forward(request, response);
                    }
                    
                    //Thêm vào giỏ hàng
                    String action = request.getParameter("action");
                    if(action!=null && action.equals("Them"))
                    {
                        int MaPhieu = 0;
                        String maGiay = request.getParameter("MaPhieu");
                        if(maGiay!=null){
                            MaPhieu = Integer.parseInt(maGiay);
                        }
                        PhieuPOJO p = PhieuDAO.GetPhieu(MaPhieu);
                        long current_time = System.currentTimeMillis()/1000;
                        long ketthuc = p.getKetThucKhuyenMai().getTime()/1000;
                        long range = ketthuc - current_time;
                        if(p.getSoLuongMua()<p.getSoLuongQuyDinh() && range>0)
                        {
                            boolean kq = false;
                            for(int i=0;i<gioHang.size();i++)
                            {
                                PhieuPOJO g1 = gioHang.get(i);
                                if(g1.getMaPhieu()==Integer.parseInt(maGiay))
                                {
                                    g1.setSoLuongQuyDinh(g1.getSoLuongQuyDinh()+1);    
                                    double tongtien = g1.getGiaBan()*g1.getSoLuongQuyDinh();
                                    g1.setThanhTienGioHang(tongtien);
                                    kq = true;
                                    break;
                                }                       
                            }
                            if(kq == false)
                            {
                                PhieuPOJO giay = new PhieuPOJO();
                                giay = PhieuDAO.GetPhieu(Integer.parseInt(maGiay));
                                giay.setSoLuongQuyDinh(1);
                                giay.setThanhTienGioHang(giay.getGiaBan());
                                gioHang.add(giay);
                            }
                        }
                        request.getRequestDispatcher("GioHang?Page=View").forward(request, response);
                    }
                    //Cập nhật giỏ hàng
                    if(request.getParameter("btnCapNhat")!=null)
                    {
                        /*
                         * Nếu ng` dùng nhấn cập nhật
                         * Form sẽ gửi lên server các số lượng tương ứng với các sp có trong giỏ hàng
                         * Giá trị này nằm trong phần Value của textfield SoLuong
                         */
                        String[] cacSoLuongCapNhat = request.getParameterValues("tbsoluong");
                        if(cacSoLuongCapNhat != null)
                        {
                            for(int i=0;i<gioHang.size();i++)
                            {
                                int SoLuong = Integer.parseInt(cacSoLuongCapNhat[i]);
                                gioHang.get(i).setSoLuongQuyDinh(SoLuong);
                                double tongtien = gioHang.get(i).getGiaBan()*gioHang.get(i).getSoLuongQuyDinh();
                                gioHang.get(i).setThanhTienGioHang(tongtien);
                            }
                        }
                        request.getRequestDispatcher("GioHang?Page=View").forward(request, response);
                    }
                    //Đặt hàng
                    if(request.getParameter("btnLuuGioHang")!=null)
                    {
                        if(!gioHang.isEmpty())
                        {
                            response.sendRedirect("ThongTinKH?Page=recp&m=ck");
                        }
                        else
                        {
                            response.sendRedirect("home?Page=View");
                        }
                    }
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(GioHang.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(GioHang.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
